package jnpf.service.impl;

import jnpf.util.UserProvider;
import jnpf.base.ActionResult;
import jnpf.model.page.MyPageListVO;
import jnpf.model.page.MyPageInfo;
import jnpf.model.themeLog.ThemeQuery;
import jnpf.entity.*;
import jnpf.mapper.ThemeMangeMapper;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.thememange.*;

import cn.hutool.core.util.ObjectUtil;
import jnpf.util.GeneraterSwapUtil;

import java.lang.reflect.Field;

import com.baomidou.mybatisplus.annotation.TableField;

import jnpf.model.QueryModel;

import java.util.stream.Collectors;

import jnpf.base.model.ColumnDataModel;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import jnpf.util.*;

import java.util.*;

import jnpf.base.UserInfo;
import jnpf.permission.entity.UserEntity;

/**
 * themeMange
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-04-09
 */
@Service
public class ThemeMangeServiceImpl extends ServiceImpl<ThemeMangeMapper, ThemeMangeEntity> implements ThemeMangeService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private EntityService entityService;

    @Autowired
    private ThemeMangeService themeMangeService;

    @Autowired
    private TagService tagService;

    @Override
    public List<ThemeMangeEntity> getList(ThemeMangePagination themeMangePagination) {
        return getTypeList(themeMangePagination, themeMangePagination.getDataType());
    }

    /**
     * 列表查询
     */
    @Override
    public List<ThemeMangeEntity> getTypeList(ThemeMangePagination themeMangePagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? ThemeMangeConstant.getAppColumnData() : ThemeMangeConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total = 0;
        int themeMangeNum = 0;
        QueryWrapper<ThemeMangeEntity> themeMangeQueryWrapper = new QueryWrapper<>();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(themeMangePagination.getSuperQueryJson())) {
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            String queryJson = themeMangePagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<ThemeMangeEntity> themeMangeSuperWrapper = new QueryWrapper<>();
            themeMangeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(themeMangeSuperWrapper, ThemeMangeEntity.class, queryJson, "0"));
            int themeMangeNum1 = themeMangeSuperWrapper.getExpression().getNormal().size();
            if (themeMangeNum1 > 0) {
                List<String> themeMangeList = this.list(themeMangeSuperWrapper).stream().map(ThemeMangeEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(themeMangeList);
                intersectionSuperList.add(themeMangeList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if (superOp.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp = "";
        if (ObjectUtil.isNotEmpty(ruleJson)) {
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<ThemeMangeEntity> themeMangeSuperWrapper = new QueryWrapper<>();
            themeMangeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(themeMangeSuperWrapper, ThemeMangeEntity.class, ruleJson, "0"));
            int themeMangeNum1 = themeMangeSuperWrapper.getExpression().getNormal().size();
            if (themeMangeNum1 > 0) {
                List<String> themeMangeList = this.list(themeMangeSuperWrapper).stream().map(ThemeMangeEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(themeMangeList);
                intersectionRuleList.add(themeMangeList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if (ruleOp.equalsIgnoreCase("and")) {
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            } else {
                allRuleIDlist = allRuleList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object themeMangeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(themeMangeQueryWrapper, ThemeMangeEntity.class, themeMangePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(themeMangeObj)) {
                    return new ArrayList<>();
                } else {
                    themeMangeQueryWrapper = (QueryWrapper<ThemeMangeEntity>) themeMangeObj;
                    if (themeMangeQueryWrapper.getExpression().getNormal().size() > 0) {
                        themeMangeNum++;
                    }
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object themeMangeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(themeMangeQueryWrapper, ThemeMangeEntity.class, themeMangePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(themeMangeObj)) {
                    return new ArrayList<>();
                } else {
                    themeMangeQueryWrapper = (QueryWrapper<ThemeMangeEntity>) themeMangeObj;
                    if (themeMangeQueryWrapper.getExpression().getNormal().size() > 0) {
                        themeMangeNum++;
                    }
                }


            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(themeMangePagination.getThemeType())) {
                themeMangeNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] themeType = JsonUtil.getJsonToBean(themeMangePagination.getThemeType(), String[][].class);
                    for (int i = 0; i < themeType.length; i++) {
                        if (themeType[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(themeType[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> themeType = JsonUtil.getJsonToList(themeMangePagination.getThemeType(), String.class);
                        if (themeType.size() > 0) {
                            idList.addAll(themeType);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(themeMangePagination.getThemeType()));
                    }
                }
                themeMangeQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(ThemeMangeEntity::getThemeType, tt).or();
                    });
                });

            }

            if (ObjectUtil.isNotEmpty(themeMangePagination.getUser())) {
                themeMangeNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] user = JsonUtil.getJsonToBean(themeMangePagination.getUser(), String[][].class);
                    for (int i = 0; i < user.length; i++) {
                        if (user[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(user[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> user = JsonUtil.getJsonToList(themeMangePagination.getUser(), String.class);
                        if (user.size() > 0) {
                            idList.addAll(user);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(themeMangePagination.getUser()));
                    }
                }
                themeMangeQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(ThemeMangeEntity::getUser, tt).or();
                    });
                });

            }

            if (ObjectUtil.isNotEmpty(themeMangePagination.getThemeStatus())) {
                themeMangeNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] themeStatus = JsonUtil.getJsonToBean(themeMangePagination.getThemeStatus(), String[][].class);
                    for (int i = 0; i < themeStatus.length; i++) {
                        if (themeStatus[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(themeStatus[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> themeStatus = JsonUtil.getJsonToList(themeMangePagination.getThemeStatus(), String.class);
                        if (themeStatus.size() > 0) {
                            idList.addAll(themeStatus);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(themeMangePagination.getThemeStatus()));
                    }
                }
                themeMangeQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(ThemeMangeEntity::getThemeStatus, tt).or();
                    });
                });

            }

            if (ObjectUtil.isNotEmpty(themeMangePagination.getThemeName())) {
                themeMangeNum++;

                String value = themeMangePagination.getThemeName() instanceof List ? JsonUtil.getObjectToString(themeMangePagination.getThemeName()) : String.valueOf(themeMangePagination.getThemeName());
                themeMangeQueryWrapper.lambda().like(ThemeMangeEntity::getThemeName, value);

            }

        }
        if (!isPc) {
            if (ObjectUtil.isNotEmpty(themeMangePagination.getThemeName())) {
                themeMangeNum++;

                String value = themeMangePagination.getThemeName() instanceof List ? JsonUtil.getObjectToString(themeMangePagination.getThemeName()) : String.valueOf(themeMangePagination.getThemeName());
                themeMangeQueryWrapper.lambda().like(ThemeMangeEntity::getThemeName, value);

            }

        }
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            themeMangeQueryWrapper.lambda().in(ThemeMangeEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            themeMangeQueryWrapper.lambda().and(t -> t.in(ThemeMangeEntity::getId, finalAllSuperIDlist));
        }
        //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)) {
            if (allRuleIDlist.size() == 0) {
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            themeMangeQueryWrapper.lambda().and(t -> t.in(ThemeMangeEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if (StringUtil.isEmpty(themeMangePagination.getSidx())) {
            themeMangeQueryWrapper.lambda().orderByDesc(ThemeMangeEntity::getId);
        } else {
            try {
                String sidx = themeMangePagination.getSidx();
                String[] strs = sidx.split("_name");
                ThemeMangeEntity themeMangeEntity = new ThemeMangeEntity();
                Field declaredField = themeMangeEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                themeMangeQueryWrapper = "asc".equals(themeMangePagination.getSort().toLowerCase()) ? themeMangeQueryWrapper.orderByAsc(value) : themeMangeQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<ThemeMangeEntity> page = new Page<>(themeMangePagination.getCurrentPage(), themeMangePagination.getPageSize());
                IPage<ThemeMangeEntity> userIPage = this.page(page, themeMangeQueryWrapper);
                return themeMangePagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<ThemeMangeEntity> list = new ArrayList();
                return themeMangePagination.setData(list, list.size());
            }
        } else {
            return this.list(themeMangeQueryWrapper);
        }
    }

    @Override
    public ThemeMangeEntity getInfo(String id) {
        QueryWrapper<ThemeMangeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ThemeMangeEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ThemeMangeEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, ThemeMangeEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(ThemeMangeEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    /**
     * 验证表单唯一字段，正则，非空 i-0新增-1修改
     */
    @Override
    public String checkForm(ThemeMangeForm form, int i) {
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }
        //主表字段验证
        if (StringUtil.isEmpty(form.getThemeName())) {
            return "主题名称不能为空";
        }
        if (StringUtil.isNotEmpty(form.getThemeName())) {
            form.setThemeName(form.getThemeName().trim());
            QueryWrapper<ThemeMangeEntity> themeNameWrapper = new QueryWrapper<>();
            themeNameWrapper.lambda().eq(ThemeMangeEntity::getThemeName, form.getThemeName());
            if (isUp) {
                themeNameWrapper.lambda().ne(ThemeMangeEntity::getId, id);
            }
            if ((int) this.count(themeNameWrapper) > 0) {
                countRecover = "主题名称不能重复";
            }
        }
        return countRecover;
    }

    /**
     * 新增修改数据(事务回滚)
     *
     * @param id
     * @param themeMangeForm
     * @return
     */
    @Override
    @Transactional
    public void saveOrUpdate(ThemeMangeForm themeMangeForm, String id, boolean isSave) throws Exception {
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        themeMangeForm = JsonUtil.getJsonToBean(generaterSwapUtil.swapDatetime(ThemeMangeConstant.getFormData(), themeMangeForm), ThemeMangeForm.class);
        ThemeMangeEntity entity = JsonUtil.getJsonToBean(themeMangeForm, ThemeMangeEntity.class);

        if (isSave) {
            String mainId = RandomUtil.uuId();
            entity.setId(mainId);
        } else {
        }
        this.saveOrUpdate(entity);

    }

    @Override
    public Map<String, String> getThemeNamesByIds(ArrayList<String> themeIds) {
        if (themeIds == null || themeIds.isEmpty()) {
            return Collections.emptyMap();
        }
        // 借助 MyBatis-Plus 批量查询主题实体
        List<ThemeMangeEntity> themeEntities = this.listByIds(themeIds);
        // 把查询结果转化为 Map
        Map<String, String> themeNameMap = new HashMap<>();
        for (ThemeMangeEntity themeEntity : themeEntities) {
            themeNameMap.put(themeEntity.getId(), themeEntity.getThemeName());
        }
        return themeNameMap;
    }

    @Override
    public ActionResult getEntityCount(String themeId) {
        QueryWrapper<EntityEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EntityEntity::getThemeId, themeId);
        long count = entityService.count(queryWrapper);
        return ActionResult.success(count);
    }


    @Override
    public MyPageListVO<ThemeMangeEntity> searchList(ThemeQuery themeMangePagination) {
        Boolean isAll = themeMangePagination.getIsAll();
        if (isAll) {
            List<ThemeMangeEntity> list = themeMangeService.list();
            MyPageListVO<ThemeMangeEntity> result = new MyPageListVO<>();
            result.setList(list);
            result.setPagination(new MyPageInfo((long) list.size()));
            return result;
        } else {
            // 构建查询参数
            QueryWrapper<ThemeMangeEntity> queryWrapper = new QueryWrapper<>();
            if (StringUtil.isNotEmpty(themeMangePagination.getThemeType())) {
                queryWrapper.lambda().eq(ThemeMangeEntity::getThemeType, themeMangePagination.getThemeType());
            }
            if (StringUtil.isNotEmpty(themeMangePagination.getUser())) {
                queryWrapper.lambda().eq(ThemeMangeEntity::getUser, themeMangePagination.getUser());
            }
            if (StringUtil.isNotEmpty(themeMangePagination.getThemeStatus())) {
                queryWrapper.lambda().eq(ThemeMangeEntity::getThemeStatus, themeMangePagination.getThemeStatus());
            }
            if (StringUtil.isNotEmpty(themeMangePagination.getThemeName())) {
                queryWrapper.lambda().like(ThemeMangeEntity::getThemeName, themeMangePagination.getThemeName());
            }

            // 分页查询
            Page<ThemeMangeEntity> page = new Page<>(themeMangePagination.getCurrentPage(), themeMangePagination.getPageSize());
            IPage<ThemeMangeEntity> entityPage = themeMangeService.page(page, queryWrapper);

            List<ThemeMangeEntity> records = entityPage.getRecords();

            // 处理标签信息
            if (!records.isEmpty()) {
                Set<String> tagIds = records.stream()
                        .filter(entity -> StringUtil.isNotEmpty(entity.getThemeTag()))
                        .flatMap(entity -> JsonUtil.getJsonToList(entity.getThemeTag(), String.class).stream())
                        .collect(Collectors.toSet());

                Map<String, String> tagNameMap = tagIds.isEmpty() ? new HashMap<>() :
                        tagService.lambdaQuery()
                                .in(TagEntity::getId, tagIds)
                                .list()
                                .stream()
                                .collect(Collectors.toMap(TagEntity::getId, TagEntity::getName));

                records.forEach(entity -> {
                    if (StringUtil.isNotEmpty(entity.getThemeTag())) {
                        List<Map<String, String>> tagList = JsonUtil.getJsonToList(entity.getThemeTag(), String.class)
                                .stream()
                                .map(tagId -> {
                                    Map<String, String> tagMap = new HashMap<>();
                                    tagMap.put("id", tagId);
                                    tagMap.put("name", tagNameMap.getOrDefault(tagId, ""));
                                    return tagMap;
                                })
                                .collect(Collectors.toList());
                        entity.setThemeTag(JsonUtil.getObjectToString(tagList));
                    }
                });
            }

            // 构建返回结果
            MyPageListVO<ThemeMangeEntity> result = new MyPageListVO<>();
            result.setList(records);
            MyPageInfo pagination = new MyPageInfo();
            pagination.setTotal(entityPage.getTotal());
            pagination.setCurrentPage(entityPage.getCurrent());
            pagination.setPageSize(entityPage.getSize());
            result.setPagination(pagination);
            return result;
        }
    }

}
